package com.iddaa.core.service.impl;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Collection;

import net.spy.memcached.MemcachedClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.iddaa.core.annotation.Memcached;
import com.iddaa.core.annotation.MemcachedRead;
import com.iddaa.core.dao.TeamDAO;
import com.iddaa.core.domain.Team;
import com.iddaa.core.service.SolrService;
import com.iddaa.core.service.TeamService;
import com.iddaa.core.util.Constants;

@Service("teamService")
@Memcached(prefix = "Team", expiration = Constants.Cache.TEAM_EXPIRETIME)
public class TeamServiceImpl implements TeamService {

	@Autowired
	private TeamDAO teamDAO;

	@Autowired
	private SolrService solrService;

	@Override
	public void deleteTeam(Long id) {
		teamDAO.delete(findById(id));
		solrService.updateSolr(id,"Team");
		deleteCache(id);
	}

	@Override
	@MemcachedRead
	public Team findById(Long id) {
		return teamDAO.getById(id);
	}

	@Override
	public Collection<Team> loadAll() {
		return teamDAO.loadAll();
	}

	@Override
	public void saveTeam(Team team) {
		teamDAO.saveOrUpdate(team);
		solrService.updateSolr(team.getId(), team.getName(), "Team");
		evictCache(team);
	}

	@Async
	public void evictCache(Team team) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.set("Team:" + team.getId(), Constants.Cache.TEAM_EXPIRETIME, team);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Async
	public void deleteCache(Long id) {
		MemcachedClient memcachedClient = null;
		try {
			memcachedClient = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
			memcachedClient.delete("Team:" + id);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
